<template>
	<view class="warp">
		<!-- #ifdef APP -->
		<statusBar></statusBar>
		<!-- #endif -->

		<!-- banner -->
		<unicloud-db ref="bannerdb" v-slot:default="{data, loading, error, options}" collection="opendb-banner"
			field="_id,bannerfile,open_url,title" @load="onqueryload">
			<!-- 当无banner数据时显示占位图 -->
			<image v-if="!(loading||data.length)" class="banner-image" src="/static/uni-center/headers.png"
				mode="aspectFill" :draggable="false" />

			<swiper v-else class="swiper-box" @change="changeSwiper" :current="current" indicator-dots>
				<swiper-item v-for="(item, index) in data" :key="item._id">
					<image class="banner-image" :src="item.bannerfile.url" mode="aspectFill"
						@click="clickBannerItem(item)" :draggable="false" />
				</swiper-item>
			</swiper>
		</unicloud-db>
		<!-- 宫格 -->
		<uni-section title="派单目录" type="line"></uni-section>
		<view class="grid-body">
			<uni-grid :column="4" :showBorder="false">
				<uni-grid-item v-for="(item, index) in commonList" :key="index">
					<view class="grid-item-box" @click="clickGridItem(item, index)">
						<uni-icons :type="item.iconType" :size="30"></uni-icons>
						<text class="text">{{ item.text }}</text>
					</view>
				</uni-grid-item>
			</uni-grid>
		</view>
	</view>
	<unicloud-db ref='udb' v-slot:default="{data,pagination,hasMore, loading, error}" @error="onqueryerror"
		:collection="colList" :page-size="10">

		<uni-list class="uni-list" :border="false">
			<!-- 列表渲染 -->
			<uni-list-item v-for="(item,index) in data" showArrow :clickable="true" :key="index"
				orderby="create_date desc" @click="handleItemClick(item._id,item.status)"
				:title="`${item.type_id[0]?.text}|${item.store_id[0]?.text}`"
				:rightText="enumConverter.status_valuetotext[item.status]">

			</uni-list-item>

		</uni-list>
	</unicloud-db>
	<!-- 宫格 -->
	<uni-section title="执行通道" type="line"></uni-section>
	<view class="grid-body">
		<uni-grid :column="4" :showBorder="false">
			<uni-grid-item v-for="(item, index) in gridList" :key="index">
				<view class="grid-item-box" @click="clickGridItem(item, index)">
					<uni-icons :type="item.iconType" :size="30"></uni-icons>
					<text class="text">{{ item.text }}</text>
				</view>
			</uni-grid-item>
		</uni-grid>
	</view>
</template>

<script>
	// #ifdef APP
	import statusBar from "@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-status-bar";
	// #endif
	import {
		mutations,
		store
	} from '@/uni_modules/uni-id-pages/common/store'
	import {
		enumConverter
	} from '../../js_sdk/validator/yycw_car_service_order.js'
	const db = uniCloud.database()
	
	export default {
		// #ifdef APP
		components: {
			statusBar
		},
		// #endif
		data() {
			return {
				commonList: [],
				gridList: [],
				current: 0,
				where: `user_id=="${store.userInfo._id}" && status >= 0`,
				orderBy: 'status, create_date desc',
				enumConverter: {
					// 将scheme enum 属性静态数据中的value转成text
					...enumConverter
				},
			}
		},
		onShow() {
		},
		onLoad() {
			uni.showShareMenu({
				//开启后，wxmp进入可以在 App.onLaunch 或 App.onShow 获取到一个 shareTicket。通过调用 wx.getShareInfo 接口传入此 shareTicket 可以获取到转发信息
				withShareTicket: true,
				menus: ['shareAppMessage', 'shareTimeline']
			})
			const that = this
			this.commonList = [{
				text: '任务派单',
				path: '/pages/yycw_car_service_order/add',
				iconType: 'person-filled',
				tempIds: ['mjGiya6sEGbNqdJ7olO7IqBXSCXj-XVdnOlE_3XJwy8',
					'Amqj8HYXmD0KAuZ7-eWqhMZFQ_HqpUBPrA_hHXQFfs4'
				]
			}, {
				text: '三期名片',
				path: '/pages/yycw-car-archives/work',
				iconType: 'person-filled',
				// tempIds: []
			}]
			let baseGridList = [{
					text: '任务初审',
					path: '/pages/yycw_car_service_order/list',
					iconType: 'person-filled',
					role: 'auditor',
					// tempIds: ['mjGiya6sEGbNqdJ7olO7ImcuOei4tMNzZWDdOAapMcA']
				},
				{
					text: '车管家任务',
					path: '/pages/yycw_car_service_order/list',
					iconType: 'person-filled',
					role: 'butler',
					tempIds: ['T_GL6442fynSz-3nGOZlsaAWzxCrrVyJ4BIBKNRvXQo',
						'H8eA0MIzOkqWsiiFWDsDWTQZlCkntzUvdB6XDYmzJ-c',
						'JUBkII7UkA83l6PrrhUQ8iOp4iXZMPugMtjuP7jl43w'
					]
				}, {
					text: '稽核介入',
					// path: '/pages/yycw_car_service_order/serviceList', //supervisorList',
					path: '/pages/yycw_car_service_order/list',
					iconType: 'person-filled',
					role: 'supervisor',
					// tempIds: ['mjGiya6sEGbNqdJ7olO7ImcuOei4tMNzZWDdOAapMcA']
				}, {
					text: '财务审核',
					path: '/pages/yycw_car_service_order/list',
					iconType: 'person-filled',
					role: 'officer',
					tempIds: ['JYrmMPR6Fs8KdyFb4Y2t5gc2Tq88Qm3dGvn4qmS2w70']
				},
			]
			this.gridList = baseGridList
			//.filter(item => 
			//   !item.role || this.uniIDHasRole(item.role))
			// if (userInfo.role) {
			// 	setInterval(() => this.$refs.udb.refresh(), 60 * 1000)
			// }
		},
		computed: {
			colList() {
				return [
					db.collection('yycw_car_service_order')
					.where(this.where)
					.field('type_id,create_date,store_id,status').limit(3).getTemp(),
					db.collection('yycw_car_service_type').field('_id,service_name as text').getTemp(),
					db.collection('yycw_store').field('_id,store_name as text').getTemp()
				]
			}
		},
		methods: {
			uniIDHasRole(role) {
				const userInfo = uniCloud.getCurrentUserInfo()
				return (userInfo['role'] || []).includes(role)
			},
			/**
			 * banner加载后触发的回调
			 */
			onqueryload(data) {},
			changeSwiper(e) {
				this.current = e.detail.current
			},
			/**
			 * 点击banner的处理
			 */
			clickBannerItem(item) {
				// 有外部链接-跳转url
				// if (item.open_url) {
				// 	uni.navigateTo({
				// 		url: '/uni_modules/uni-id-pages/pages/common/webview/webview?url=' + item.open_url + '&title=' + item.title,
				// 		success: res => {},
				// 		fail: () => {},
				// 		complete: () => {}
				// 	});
				// }
				// 其余业务处理
			},
			clickGridItem(item, index) {

				// console.log(item)
				// 权限判断
				if (item.role) {
					if (!store.hasLogin) {
						mutations.logout()
						return
					}
					if (!this.uniIDHasRole(item.role)) {
						uni.showToast({
							title: '您没有权限访问',
							icon: 'none',
						})
						return
					}
				}

				if (item.tempIds) {
					uni.requestSubscribeMessage({
						tmplIds: item.tempIds, // 改成你的小程序订阅消息模板id
						success: (res) => {},
						fail: (res) => {
							// console.debug('fail:' + JSON.stringify(res))
							uni.showToast({
								title: '订阅消息模板错误',
								icon: 'error',
								duration: 1000
							});
							if (20001 === res.errCode) {
								console.debug('sub fail no temp return')
							}

						},
						complete: () => {
							if (item.path) {
								//如果有 path 属性，则跳转到指定页面
								if (item.role) {
									this.toPage(item.path, `role=${item.role}`)
								} else {
									this.toPage(item.path)
								}
								
							} else {
								// 如果没有 pageUrl 属性，则显示提示
								uni.showToast({
									title: '功能建设中~',
									icon: 'none',
								})
							}
						}
					})
				} else {
					if (item.path) {
						//如果有 path 属性，则跳转到指定页面
						if (item.role) {
							this.toPage(item.path, `role=${item.role}`)
						} else {
							this.toPage(item.path)
						}
					} else {
						// 如果没有 pageUrl 属性，则显示提示
						uni.showToast({
							title: '功能建设中~',
							icon: 'none',
						})
					}
				}
			},
			toPage(url, params){
				if (params) url += '?' + params
				uni.navigateTo({
					url: url,
					fail: (err) => {
						console.error('导航失败:', err);
						uni.showToast({
							title: '页面跳转失败',
							icon: 'none'
						})
					}
				})
			},
			handleItemClick(id, status) {
				uni.navigateTo({
					url: '/pages/yycw_car_service_order/detail?id=' + id,
				})
			},
			onqueryerror(e) {
				console.error(e)
			},
		}
	}
</script>

<style>
	/* #ifndef APP-NVUE */
	page {
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		background-color: #fff;
		min-height: 100%;
		height: auto;
	}

	view {
		font-size: 14px;
		line-height: inherit;
	}

	.example-body {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		flex-wrap: wrap;
		justify-content: center;
		padding: 0;
		font-size: 14px;
		background-color: #ffffff;
	}

	/* #endif */

	.section-box {
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 20rpx;
	}

	.decoration {
		width: 4px;
		height: 12px;
		border-radius: 10px;
		background-color: #2979ff;
	}

	.section-text {
		color: #333;
		margin-left: 15rpx;
	}

	/* #ifdef APP-NVUE */
	.warp {
		background-color: #fff;
	}

	/* #endif */

	.example-body {
		flex-direction: column;
		padding: 15px;
		background-color: #ffffff;
	}

	.image {
		width: 50rpx;
		height: 50rpx;
	}

	.big-number {
		font-size: 50rpx;
		font-weight: 700;
		font-stretch: condensed;
		font-style: oblique;
	}

	.text {
		text-align: center;
		font-size: 26rpx;
		margin-top: 10rpx;
	}

	.example-body {
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
	}

	.grid-item-box {
		flex: 1;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 15px 0;
	}

	.banner-image {
		width: 100%;
		height: 400rpx;
	}

	.swiper-box {
		height: 400rpx;
	}

	.search-icons {
		padding: 16rpx;
	}

	.search-container-bar {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		justify-content: center;
		align-items: center;
		position: fixed;
		left: 0;
		right: 0;
		z-index: 10;
		background-color: #fff;
	}

	/* #ifndef APP-NVUE || VUE3*/
	::v-deep

	/* #endif */
	.uni-searchbar__box {
		border-width: 0;
	}

	/* #ifndef APP-NVUE || VUE3 */
	::v-deep

	/* #endif */
	.uni-input-placeholder {
		font-size: 28rpx;
	}
</style>